package com.exam.api.modules.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.exam.api.common.utils.ListDiffUtil;
import com.exam.api.modules.system.domain.TblRoleMenu;
import com.exam.api.modules.system.mapper.TblRoleMenuMapper;
import com.exam.api.modules.system.service.TblRoleMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 角色菜单关系逻辑接口类实现类
 *
 * @author bcheng
 */
@Slf4j
@Service
public class TblRoleMenuServiceImpl extends ServiceImpl<TblRoleMenuMapper, TblRoleMenu> implements TblRoleMenuService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveRoleMenu(Long roleId, List<Long> menuIds) {
        if (CollUtil.isEmpty(menuIds)) {
            lambdaUpdate()
                    .eq(TblRoleMenu::getRoleId, roleId)
                    .remove();
            return;
        }
        //1. 查询出所有的角色菜单关系
        Set<Long> originalList = lambdaQuery()
                .eq(TblRoleMenu::getRoleId, roleId)
                .select(TblRoleMenu::getMenuId)
                .list()
                .stream()
                .map(TblRoleMenu::getMenuId)
                .collect(Collectors.toSet());
        //2. 找出新增的
        List<Long> added = ListDiffUtil.findAdded(originalList, menuIds, (item) -> item);
        if (CollUtil.isNotEmpty(added)) {
            List<TblRoleMenu> addedList = added.stream()
                    .map(menuId -> {
                        TblRoleMenu roleMenu = new TblRoleMenu();
                        roleMenu.setRoleId(roleId);
                        roleMenu.setMenuId(menuId);
                        return roleMenu;
                    }).toList();
            saveBatch(addedList);
            log.info(" <<<=== 新增角色菜单关系  角色id : {} 菜单： {}", roleId, added);
        }
        //3. 找出删除的
        List<Long> deleted = ListDiffUtil.findDeleted(originalList, menuIds, (item) -> item);
        if (CollUtil.isNotEmpty(deleted)) {
            lambdaUpdate()
                    .eq(TblRoleMenu::getRoleId, roleId)
                    .in(TblRoleMenu::getMenuId, deleted)
                    .remove();
            log.info(" <<<=== 删除角色菜单关系  角色id : {} 菜单： {}", roleId, deleted);
        }
    }
}
